class ProgramsController < ApplicationController

  skip_before_filter :setup, :only => [:new, :create]
  before_filter :ensure_application_has_one_program, :only => [:new, :create, :destroy]

  def index
    @programs = Program.find(:all)
  end

  def show
    @program = Program.find(params[:id])
    @sites = @program.sites
    add_page_token(@program.name)
  end

  def new
    @program = Program.new
  end

  def edit
    @program = Program.find(params[:id])
    add_page_token(@program.name)
  end

  def create
    @program = Program.new(params[:program])

    if @program.save
      flash[:notice] = 'Program was successfully created.'
      redirect_to home_path
    else
      render :action => "new"
    end
  end

  def update
    @program = Program.find(params[:id])
    add_page_token(@program.name)

    if @program.update_attributes(params[:program])
      flash[:notice] = 'Program was successfully updated.'
      redirect_to(@program)
    else
      render :action => "edit"
    end
  end

  def destroy
    @program = Program.find(params[:id])
    @program.destroy

    redirect_to programs_path
  end

  private

    def ensure_application_has_one_program
      if Program.count == 1
        flash[:error] = 'The program has already been setup.'
        redirect_to home_path
      end
    end

end
